package org.oc.qaq.service.Impl;

import lombok.extern.slf4j.Slf4j;
import org.oc.qaq.config.EditorConfig;
import org.oc.qaq.config.OnlyOfficeConfig;
import org.oc.qaq.context.UserContext;
import org.oc.qaq.entity.FileEntity;
import org.oc.qaq.entity.User;
import org.oc.qaq.entity.onlyOffice.UserInfo;
import org.oc.qaq.mapper.FileMapper;
import org.oc.qaq.entity.onlyOffice.Document;
import org.oc.qaq.mapper.UserMapper;
import org.oc.qaq.service.FileService;
import org.oc.qaq.service.OnlyOfficeService;
import org.oc.qaq.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;

@Service
@Slf4j
public class OnlyOfficeServiceImpl implements OnlyOfficeService {

    @Autowired
    private AliOssUtil ossUtil;

    @Autowired
    private FileService fileService;

    @Autowired
    private EditorConfig editorConfig;

    @Autowired
    private DocumentService documentService;

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public OnlyOfficeConfig LoadConfig(String fileId) {
        log.info("载入编辑器配置，打开文件ID：{}", fileId);

        FileEntity file = fileService.getOneById(fileId);
        User curUser = userMapper.selectOneById(UserContext.getCurrentId());

        OnlyOfficeConfig config = new OnlyOfficeConfig();
        Document document = new Document();
        UserInfo userInfo = new UserInfo();

        document.setKey(file.getId());
        document.setFileType(file.getType());
        document.setTitle(file.getName());
        document.setUrl(file.getUrl());

        userInfo.setId(curUser.getId());
        userInfo.setName(curUser.getUsername());
        userInfo.setImage(curUser.getAvatar());

        editorConfig.setUser(userInfo);

        config.setDocument(document);
        config.setDocumentType(document.getFileType());

        config.setEditorConfig(editorConfig);

        String type = document.getFileType();
        if (type.equals("doc") || type.equals("docx")) {
            config.setDocumentType("word");
        }

        if (type.equals("xls") || type.equals("xlsx")) {
            config.setDocumentType("cell");
        }

        if (type.equals("ppt") || type.equals("pptx")) {
            config.setDocumentType("slide");
        }

        if (type.equals("pdf")) {
            config.setDocumentType("pdf");
        }

        log.info("载入配置为：{}", config);

        return config;
    }

    @Override
    public ResponseEntity<Map<String, Object>> callback(Map<String, Object> data) throws IOException {

        int status = (int) data.get("status");
        String fileId = (String) data.get("key");

        if (status == 2 || status == 6) { // 文档已保存
            String downloadUrl = (String) data.get("url");
            String fileName = fileId + "." + data.get("filetype");

            // 上传到 OSS
            try (InputStream inputStream = new URL(downloadUrl).openStream()) {
                String ossUrl = ossUtil.upload(inputStream.readAllBytes(), fileName);

                // 保存文件信息到数据库
                fileService.updateFileUrl(fileId, ossUrl);

                // 保存文件信息到Elasticsearch
                FileEntity file = fileMapper.selectFileById(fileId);
                documentService.asyncSave(file);

                log.info("文档已保存到 OSS: {}", ossUrl);
            }
        }

        return ResponseEntity.ok(Map.of("error", 0));
    }
}
